package me.pppploi8.webmcs.main.urlmapping;

import com.alibaba.fastjson.JSON;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

import me.pppploi8.webmcs.http.jetty.HttpUrlMapping;
import me.pppploi8.webmcs.minecraft.server.core.McServerCore;
import me.pppploi8.webmcs.minecraft.server.core.McServerFactory;

/**
 * 软件设置相关服务接口
 * @author pppploi8
 */
public class WebmcsSettingService extends HttpUrlMapping{
    private McServerCore msc;
    private String curPath;
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    public WebmcsSettingService(){
        this.msc = McServerFactory.getMcServerCore();
        this.curPath = msc.getServerPath().getParent();
    }
    /**
     * 获取当前设置
     * @return 返回一个对象集合，按key=value的方式
     */
    public Object getsetting(){
        Map<String,Object> map = new HashMap<>();
        map.put("status", true);
        try {
            File file = new File(curPath + "/config.properties");
            Properties p = new Properties();
            InputStream is = new FileInputStream(file);
            p.load(is);
            is.close();
            Enumeration<?> names = p.propertyNames();
            while(names.hasMoreElements()){
                String key = (String)names.nextElement();
                map.put(key, p.getProperty(key));
            }
        }catch(Exception e){}
        return map;
    }
    /**
     * 设置参数，要求传递一个json={json}数据
     * @return
     */
    public String setsetting(){
        Properties p = new Properties();
        try {
            String json = getRequest().getParameter("json");
            @SuppressWarnings("unchecked")
			Map<String,String> jsonObject = (Map<String, String>)JSON.parse(json);
            for (Map.Entry<String,String> entry : jsonObject.entrySet()) { 
                if (entry.getKey().equals("javaPath")){
                    p.setProperty(entry.getKey(), entry.getValue());
                    msc.setJavaPath(entry.getValue());
                }else if (entry.getKey().equals("jarPath")){
                    p.setProperty(entry.getKey(), entry.getValue()==null?"Start.jar":entry.getValue());
                    msc.setJarFile(entry.getValue());
                }else if (entry.getKey().equals("javaParam")){
                    p.setProperty(entry.getKey(), entry.getValue());
                    msc.setJavaParam(entry.getValue());
                }else if (entry.getKey().equals("startParam")){
                    p.setProperty(entry.getKey(), entry.getValue());
                    msc.setStartParam(entry.getValue());
                }else if (entry.getKey().equals("maxMemory")){
                    p.setProperty(entry.getKey(), entry.getValue());
                    msc.setMaxMemory(entry.getValue());
                }
                
            }    
        }catch(Exception e){ 
        	e.printStackTrace();
            return "{\"status\":false,\"msg\":\"DATAERROR\"}";
        }
        try {
            File file = new File(curPath + "/config.properties");
            if (!file.exists())
                file.createNewFile();
            OutputStream os = new FileOutputStream(file);
            p.store(os, null);
            os.close();
        } catch (Exception e) {
        	e.printStackTrace();
            return "{\"status\":false,\"msg\":\"SAVEERROR\"}";
        }
        return "{\"status\":true}";
    }
    /**
     * 获取文件名，需要传递path，如果路径不存在则显示根目录
     * @return 
     */
    public Object getfiles(){
        Map<String,Object> map = new HashMap<>();
        List<String[]> list = new ArrayList<>();
        map.put("status", true);
        map.put("files", list);
        String path = getRequest().getParameter("path");
        File[] roots = File.listRoots();
        File file = null;
        if (path != null && !path.equals("")){
            file = new File(path);
        }
        if (file == null || !file.exists()){
            list.add(new String[]{"","..","",""});
            //输出根目录
            for (File root : roots) {
                String[] l = new String[4];
                l[0] = root.getPath().replaceAll("\\\\", "/");//因为Windows兼容/路径，所以统一替换成/路径
                l[1] = "Dir";
                l[2] = getTimeString(root.lastModified());
                l[3] = l[0];
                list.add(l);
            }
        }else{
            String parent = file.getParent();
            list.add(0,new String[]{parent==null?"":parent.replaceAll("\\\\", "/"),"..","",""});
            //输出file目录
            File[] files = file.listFiles();
            if (files != null) {
                for (File f : files) {
                    String[] l = new String[4];
                    if (f.isDirectory()) {
                        l[0] = f.getPath().replaceAll("\\\\", "/");
                        l[1] = "Dir";
                        l[2] = getTimeString(f.lastModified());
                        l[3] = f.getName();
                        list.add(l);
                    } else if (f.getName().toLowerCase().startsWith("java")){
                        l[0] = f.getPath().replaceAll("\\\\", "/");
                        l[1] = "File";
                        l[2] = getTimeString(f.lastModified());
                        l[3] = f.getName();
                        list.add(l);
                    }
                }
            }
        }
        return map;
    }
    public Object uploadjar(){
    	Map<String,Object> map = new HashMap<>();
    	map.put("status", false);
    	//基于Commons-FileUpload包读取文件
    	if(ServletFileUpload.isMultipartContent(getRequest())){
    		try{
    			FileItemFactory factory = new DiskFileItemFactory();
    			ServletFileUpload fileUpload = new ServletFileUpload(factory);
    			List<FileItem> list = fileUpload.parseRequest(getRequest());
    			if (list.size() == 0){
    				throw new Exception("未正确上传文件！");
    			}
    			for(FileItem file : list){
    				if ("file".equals(file.getFieldName())){
    					msc.getServerPath().mkdirs();
    					String fileName = file.getName();
    					if (!fileName.toLowerCase().endsWith(".jar")){
    						map.put("msg", "TYPEERROR");
    						return map;
    					}
    		            File destFile = new File(msc.getServerPath().getAbsolutePath() + "/" + file.getName());
    		            if (destFile.exists()){
    		            	map.put("msg", "FILEREPEAT");
    		            	return map;
    		            }else{
    		            	FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
    		            }
    				}
    			}
    			map.put("status", true);
    		}catch(Exception e){
    			e.printStackTrace();
        		map.put("msg", "EXCEPTION");
    		}
    	}else{
    		map.put("msg", "CHECKERROR");
    	}
    	return map;
    }
    
    public Object getjar(){
    	Map<String,Object> map = new HashMap<>();
		map.put("status", true);
    	try{
    		File[] files = msc.getServerPath().listFiles();
    		List<String> list = new ArrayList<String>();
       		for(File f : files){
    			if (f.getName().toLowerCase().endsWith(".jar"))
    				list.add(f.getName());
    		}
    		map.put("files", list);
    	}catch(Exception e){
    		map.put("files", new String[0]);
    	}
    	return map;
    }
    
    private String getTimeString(long time){
        return sdf.format(time);
    }
}
